﻿using MqttClient.Code;
using MQTTnet;
using MQTTnet.Protocol;
using MQTTnet.Server; 
using System.Text;

namespace MqttService.Code 
{
    public class MqttManager: IMqttManager
    {
        private readonly ILogger<MqttManager> _logger; 
        public MqttManager(ILogger<MqttManager> logger)
        {
            _logger = logger; 
        }
        public async Task PublishData(string topic, string data)
        {
            _logger.LogInformation(topic,data);

            var message = new MqttApplicationMessage
            {
                Topic = topic,
                Payload = Encoding.Default.GetBytes(data),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                Retain = true  // 服务端是否保留消息。true为保留，如果有新的订阅者连接，就会立马收到该消息。
            };
           await  MqttClientService._mqttClient.PublishAsync(message); 
        }
    }
}
